<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单编号" prop="sourceCode">
        <el-input v-model="queryParams.sourceCode" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="来源单据" prop="orderSource">
        <el-select v-model="queryParams.orderSource" placeholder="请选择来源单据" style="width: 180px;">
          <el-option v-for="dict in mes_workorder_sourcetype" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="产品编号" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="批次号" prop="batchCode">
        <el-input v-model="queryParams.batchCode" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input v-model="queryParams.clientName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型" prop="workorderType">
        <el-select v-model="queryParams.workorderType" placeholder="请选择类型" style="width: 180px;">
          <el-option v-for="dict in mes_workorder_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
        <!-- <el-input v-model="queryParams.workorderType" placeholder="请选择工单类型" clearable @keyup.enter.native="handleQuery" /> -->
      </el-form-item>
      <el-form-item label="需求日期" prop="requestDate">
        <el-date-picker v-model="queryParams.requestDate" clearable type="date" value-format="yyyy-MM-dd"
          placeholder="请选择需求日期" />
      </el-form-item>
      <el-form-item label="业务员" prop="clerkName">
        <el-input v-model="queryParams.clerkName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
        <el-button size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['mes:pro:workorder:add']" type="success" size="mini"
          @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['mes:pro:workorder:remove']" type="danger" size="mini" :disabled="multiple"
          @click="handleDelete">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['mes:pro:workorder:export']" type="primary" size="mini" plain :disabled="!ids.length"
          @click="handleExport">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['mes:pro:workorder:download']" type="primary" size="mini" plain :disabled="flowcard"
          @click="downloads">打印
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['mes:pro:market:add']" type="danger" size="mini" style="color: #fff;"
          @click="marketGet">销售订单
        </el-button>
      </el-col>
    </el-row>
    <el-table ref="product" v-loading="loading" border :height="tableHeight" :data="workorderList" lazy :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChild' }" :row-key="getRowKeys"
      @sort-change="handleSortChange" @select="selectRow" @select-all="selectAllRow"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :reserve-selection="true" />
      <el-table-column label="工单编码" width="220px" prop="workorderCode">
        <template  #default="scope">
          <div v-hasPermi="['mes:pro:workorder:query']" class="div_tre" @click="handleView(scope.row)">
            {{ scope.row?.workorderCode || '--' }}
          </div>
          <div class="device-state">
            <span v-show="scope.row.attr1 == 0 && scope.row.attr1" class="device-state-color1">逾期{{ scope.row.attr3 || 0
            }}天</span>
            <span v-show="scope.row.attr1 == 1 && scope.row.attr1" class="device-state-color2">{{ scope.row.attr3 || 0
            }}天后到期</span>
            <span v-show="scope.row.isBudan == 1" class=" device-state-color2">补货</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="工单名称" width="200" prop="workorderName" :show-overflow-tooltip="true" />
      <el-table-column label="产品编号" width="120" prop="productCode" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" sortable="custom" width="200" prop="productName" :show-overflow-tooltip="true" />
      <el-table-column label="订单编号" width="180" :formatter="dataformatter" prop="sourceCode"
        :show-overflow-tooltip="true" />
      <el-table-column label="批次号" width="180" :formatter="dataformatter" prop="batchCode"
        :show-overflow-tooltip="true" />
      <el-table-column label="工单类型" prop="workorderType">
        <template #default="scope">
          <dict-tag :options="mes_workorder_type" :value="scope.row.workorderType" />
        </template>
      </el-table-column>
      <el-table-column label="工单来源" prop="orderSource" :formatter="orderSource" width="140" />
      <el-table-column label="规格型号" prop="productSpc" :formatter="dataformatter" :show-overflow-tooltip="true" />
      <el-table-column label="单位" prop="measureName" />
      <el-table-column label="客户编码" prop="clientCode" :formatter="dataformatter" />
      <el-table-column label="需求日期" sortable="custom" prop="requestDate" width="180" :formatter="requestDate" />
      <el-table-column label="业务员" prop="clerkName" :formatter="dataformatter" :show-overflow-tooltip="true"
        fixed="right" />
      <el-table-column label="客户名称" prop="clientName" :formatter="dataformatter" :show-overflow-tooltip="true"
        fixed="right" />
      <el-table-column label="工单数量" width="120" sortable="custom" prop="quantity" fixed="right" />
      <!-- <el-table-column label="调整数量" :formatter="quantityChanged" prop="quantityChanged" /> -->
      <el-table-column label="生产产量" width="100px" prop="quantityProduced" fixed="right" />
      <el-table-column label="单据状态" prop="status" fixed="right">
        <template #default="scope">
          <dict-tag :options="mes_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="230" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.status == 'PREPARE'" v-hasPermi="['mes:pro:workorder:edit']" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.status == 'CONFIRMED' && scope.row.workorderType == 'SELF'"
            v-hasPermi="['mes:pro:workorder:add']" size="mini" type="text" @click="handleAdd(scope.row)">新增
          </el-button>
          <el-button v-if="scope.row.status == 'CONFIRMED'" v-hasPermi="['mes:pro:workorder:update']" size="mini"
            type="text" @click="handleFinish(scope.row)">完成
          </el-button>
          <el-button v-if="scope.row.status == 'PREPARE'" v-hasPermi="['mes:pro:workorder:remove']" size="mini"
            type="text" style="color: #ff2224;" @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button v-hasPermi="['mes:pro:workorder:download']" size="mini" type="text"
            @click="downloadView(scope.row)">打印
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page-sizes="[20, 50, 100]" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />
    <el-dialog title="打印" :visible.sync="preview" width="1080px" append-to-body>
      <div>
        <iFrame :src="textVisibleURl" style="height: 62vh;" />
      </div>
    </el-dialog>
    <!-- 添加或修改生产工单对话框 -->
    <el-drawer :title="title" v-model="open" size="60%" append-to-body :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-right: 20px;">
        <el-row v-if="optType == 'add'">
          <el-col :span="8">
            <el-form-item label="工单编码" prop="workorderCode">
              <el-input v-model="form.workorderCode" :readonly="optType == 'view'" placeholder="请输入工单编码" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="20px">
              <el-switch v-if="optType != 'view' && form.status == 'PREPARE'" v-model="autoGenFlag" active-color="#13ce66"
                active-text="自动生成" @change="handleAutoGenChange(autoGenFlag)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input v-model="form.workorderName" :readonly="optType == 'view'" placeholder="请输入工单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="optType == 'view' || optType == 'edit'">
          <el-row>
            <div style="display: flex;width:100%">
              <div style="width:50%;">
                <div style="display:block">
                  <el-col :span="16">
                    <el-form-item label="工单编码" prop="workorderCode">
                      <el-input v-model="form.workorderCode" :readonly="optType == 'view'" placeholder="请输入工单编码" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label-width="80">
                      <el-switch v-if="optType != 'view' && form.status == 'PREPARE'" v-model="autoGenFlag"
                        :disabled="optType == 'view'" active-color="#13ce66" active-text="自动生成"
                        @change="handleAutoGenChange(autoGenFlag)" />
                    </el-form-item>
                  </el-col>
                </div>
                <div style="display:block">
                  <!-- <el-row> -->
                  <el-col :span="24">
                    <el-form-item label="工单名称" prop="workorderName">
                      <el-input v-model="form.workorderName" :readonly="optType == 'view'" placeholder="请输入工单名称" />
                    </el-form-item>
                  </el-col>
                  <!-- </el-row> -->
                </div>
              </div>
              <div style="width:50%;">
                <el-col :span="24" style="margin-left: 20%;">
                  <img :src="baseUrl + form.attr2" style="width: 100px;height:100px ;display: block;">
                  <el-button v-hasPermi="['mes:pro:workorder:download']" size="mini" type="text" style="color: #ff2224;"
                    @click="downloadView(form)">打印
                  </el-button>
                </el-col>
              </div>
            </div>
          </el-row>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="来源类型" prop="orderSource">
              <el-radio-group v-if="optType == 'view'" v-model="form.orderSource" disabled>
                <el-radio v-for="dict in mes_workorder_sourcetype" :key="dict.value" :label="dict.value">{{
                  dict.label }}
                </el-radio>
              </el-radio-group>
              <el-radio-group v-else v-model="form.orderSource">
                <el-radio v-for="dict in mes_workorder_sourcetype" :key="dict.value" :label="dict.value"
                  :disabled="(dict.value == 'ERP') || (form.orderSource == 'ERP')">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.orderSource == 'ORDER' || form.orderSource == 'ERP'" :span="8">
            <el-form-item label="订单编号" prop="sourceCode">
              <el-input v-model="form.sourceCode" :readonly="optType == 'view'" placeholder="请输入订单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" disabled placeholder="请选择单据状态" style="width: 100%;">
                <el-option v-for="dict in mes_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单类型" prop="workorderType">
              <el-select v-model="form.workorderType" :disabled="optType == 'view'" placeholder="请选择类型">
                <el-option v-for="dict in mes_workorder_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="form.productCode" :disabled="optType == 'view'" placeholder="请选择产品">
                <el-button slot="append" :disabled="optType == 'view'" icon="el-icon-s-fold"
                  @click="handleSelectProduct" />
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <ItemSelect ref="itemSelect" @onSelected="onItemSelected" /> -->
          <el-col :span="8">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请选择产品" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="productSpc">
              <el-input v-model="form.productSpc" placeholder="请选择产品" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasureName" placeholder="请选择产品" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="材质" prop="material">
              <el-input v-model="form.material" placeholder="请输入材质" :disabled="optType == 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" :disabled="optType == 'view'" placeholder="请输入重量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单数量" prop="quantity">
              <el-input-number v-model="form.quantity" :disabled="optType == 'view'" :min="1" placeholder="请输入生产数量" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker v-model="form.requestDate" :disabled="optType == 'view'" clearable type="date"
                value-format="yyyy-MM-dd" placeholder="请选择需求日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" :disabled="optType == 'view'" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.orderSource == 'ORDER' || form.orderSource == 'ERP'">
          <el-col :span="12">
            <el-form-item label="客户编码" prop="clientCode">
              <el-input v-model="form.clientCode" :disabled="optType == 'view'" placeholder="请选择客户">
                <el-button slot="append" :disabled="optType == 'view'" icon="el-icon-s-fold"
                  @click="handleSelectClient" />
              </el-input>
              <!-- <ClientSelect ref="clientSelect" @onSelected="onClientSelected" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" readonly="readonly" placeholder="请输入客户名称"
                :disabled="optType == 'view'" />
            </el-form-item>
          </el-col>
          <el-col />
        </el-row>
        <el-row v-if="form.workorderType == 'OUTSOURCE' || form.workorderType == 'PURCHASE'">
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="vendorCode">
              <el-input v-model="form.vendorCode" :disabled="optType == 'view'" placeholder="请选择供应商">
                <el-button slot="append" icon="el-icon-s-fold" @click="handleSelectVendor" />
              </el-input>
              <!-- <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商" />
            </el-form-item>
          </el-col>
          <el-col />
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :disabled="optType == 'view'" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card">
        <el-tab-pane label="工艺流程">
          <proroute :workorder-id="form.workorderId || null" :product-id="form.productId" :opt-type="optType"
            @onSelected="prorouteSelected" />
        </el-tab-pane>
        <el-tab-pane v-if="form.workorderId != null" label="BOM组成">
          <bom ref="bomlist" :opt-type="optType" :workorder="form" @handleAddSub="handleSubAdd" />
        </el-tab-pane>
      </el-tabs>
      <div class="demo-drawer__footer" style="text-align:right;margin-right: 20px;margin-top: 20px;">
        <el-button v-if="optType == 'view' || form.status != 'PREPARE'" type="primary" @click="cancel">返回</el-button>
        <el-button v-if="form.status == 'PREPARE' && optType != 'view'" type="primary" @click="submitForm">保 存
        </el-button>
        <el-button v-if="form.status == 'PREPARE' && optType != 'view' && form.workorderId != null" type="success"
          @click="handleConfirm">确 认
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <!-- 销售订单 -->
    <el-dialog title="销售订单" v-model="market" width="1200px" append-to-body @close="findOrderClose">
      <el-form ref="findOrderqueryParams" :model="findOrderqueryParams" size="small" :inline="true" label-width="68px">
        <el-form-item label="单据日期" prop="voucherDate">
          <el-date-picker v-model="findOrderqueryParams.voucherDate" type="daterange" clearable format="yyyy-MM-dd"
            value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            style="width: 250px" />
        </el-form-item>
        <el-form-item label="单据编号" prop="code">
          <el-input v-model="findOrderqueryParams.code" placeholder="请输入单据编号" clearable
            @keyup.enter.native="marketListGet" />
        </el-form-item>
        <el-form-item label="客户" prop="clientCode">
          <el-input v-model="findOrderqueryParams.clientName" readonly placeholder="请选择客户">
            <el-button slot="append" icon="el-icon-s-fold" @click="handleSelectClient" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="marketListGet">搜索</el-button>
          <el-button size="mini" @click="marketListGetresetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="marketable" v-loading="marketloading" border height="62vh" :data="marketList"
        :row-key="marketgetRowKeys" :default-expand-all="false" :expand-row-keys="expandedRows"
        @selection-change="marketSelectionChange" @expand-change="expandGet">
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.ruleItemData">
              <el-table-column type="index" label="序号" />
              <el-table-column label="商品名称" :formatter="generalData" width="180" prop="productName"
                :show-overflow-tooltip="true" />
              <el-table-column label="单位" :formatter="generalData" width="180" prop="productBaseUomName"
                :show-overflow-tooltip="true" />
              <el-table-column label="规格型号" :formatter="generalData" width="180" prop="productSpecNo"
                :show-overflow-tooltip="true" />
              <el-table-column label="数量" :formatter="generalData" width="180" prop="baseQty"
                :show-overflow-tooltip="true" />
              <el-table-column label="单价" :formatter="generalData" width="180" prop="netPriceWithTax"
                :show-overflow-tooltip="true" />
              <el-table-column label="金额" :formatter="generalData" width="180" prop="netAmountWithTax"
                :show-overflow-tooltip="true" />
              <!-- <el-table-column label="供应商" :formatter="generalData" width="180" prop="quantity2"
                :show-overflow-tooltip="true" /> -->
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column label="单据日期" width="150" prop="voucherDate" :show-overflow-tooltip="true"
          :formatter="voucherDate" />
        <el-table-column label="单据编号" :formatter="generalData" width="180" prop="code" :show-overflow-tooltip="true" />
        <el-table-column label="业务类型" :formatter="generalData" prop="businesstypeName" :show-overflow-tooltip="true" />
        <el-table-column label="客户简称" :formatter="generalData" width="250" prop="customerName"
          :show-overflow-tooltip="true" />
        <el-table-column label="单据状态" :formatter="generalData" prop="voucherstateName" :show-overflow-tooltip="true" />
        <el-table-column label="部门" :formatter="generalData" prop="departmentName" :show-overflow-tooltip="true" />
        <el-table-column label="业务员" :formatter="generalData" prop="clerkName" :show-overflow-tooltip="true" />
        <el-table-column label="预计交货日期" :formatter="generalData" width="180" prop="deliveryDate"
          :show-overflow-tooltip="true" />
        <!-- <el-table-column label="生产工单" :show-overflow-tooltip="true">
          <template #default="scope">
            <div v-if="scope.row.status==0" style="color: #FF2224;">[新]</div>
            <div v-if="scope.row.status==1">已导入</div>
          </template>
        </el-table-column> -->
      </el-table>
      <pagination v-show="findOrderqueryParams.total > 0" :total="findOrderqueryParams.total" :page-sizes="[20, 50, 100]"
        :page.sync="findOrderqueryParams.pageNum" :limit.sync="findOrderqueryParams.pageSize"
        @pagination="marketListGet" />
      <div slot="footer">
        <div class="orderinventory">
          已选择销售订单 {{ order }} 包含存货 {{ inventory }}
        </div>
        <el-button type="danger" size="mini" style="color: #fff;" :loading="addFromloading"
          @click="addFromErpOrderGet">生成工单</el-button>
      </div>
      <!-- <ClientSelect ref="clientSelect" @onSelected="onClientSelectedOrder" /> -->
    </el-dialog>
  </div>
</template>

<script setup name="Workorder">

import {
  listWorkorder,
  getWorkorder,
  delWorkorder,
  addWorkorder,
  updateWorkorder,
  dofinish,
  exportPdf,
  findOrderList,
  findItemByCode,
  addFromErpOrder,
  getChildList,
  genCode,
  listAllUnitmeasure
} from '@/api/mes/pro/workorder'
import bom from './bom/bom.vue'
import proroute from './proroute/proroute.vue'
// import ItemSelect from '@/components/itemSelect/single.vue'
import iFrame from '@/components/iFrame/index.vue'
// import ClientSelect from '@/components/clientSelect/single.vue'
// import VendorSelect from '@/components/vendorSelect/single.vue'
import moment from 'moment'
import { watch, nextTick } from 'vue'
// import { route } from 'vue-router'

const { proxy } = getCurrentInstance()
const { mes_order_status } = proxy.useDict('mes_order_status')
const { mes_workorder_sourcetype } = proxy.useDict('mes_workorder_sourcetype')
const { mes_workorder_type } = proxy.useDict('mes_workorder_type')

const tableHeight = ref('60vh')
// 自动生成编码
const autoGenFlag = ref(false)
const optType = ref(null)
// 遮罩层
const loading = ref(true)
const addFromloading = ref(false)
// 显示搜索条件
const showSearch = ref(true)
// 非单个禁用
const single = ref(true)
// 总条数
const total = ref(0)
const multiple = ref(true)
// 流转卡
const flowcard = ref(true)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 是否显示弹出层
const preview = ref(false)
const textVisibleURl = ref(null)
const market = ref(false)
const marketloading = ref(true)
// 订单
const order = ref(0)
// 存货
const inventory = ref(0)
// 选中数组
const ids = ref([])
// 生产工单表格数据
const workorderList = ref([])

// 生产工单树选项
const workorderOptions = ref([])

const marketList = ref([])

// 单位列表
const measureOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  workorderCode: null,
  workorderName: null,
  orderSource: null,
  sourceCode: null,
  productId: null,
  productCode: null,
  productName: null,
  productSpc: null,
  unitOfMeasure: null,
  quantity: null,
  quantityProduced: null,
  quantityChanged: null,
  quantityScheduled: null,
  clientId: null,
  clientCode: null,
  clientName: null,
  requestDate: null,
  parentId: null,
  ancestors: null,
  status: null,
  sortField: null,
  isAsc: null,
  routeId: null,
  sourceCode: null,
  batchCode: null,
  parentId: 0,
  clerkName: null
})
const findOrderqueryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
  startTime: '',
  endTime: '',
  voucherDate: [],
  code: '',
  customerName: ''
})
// 表单参数
const form = ref({
  workorderId: null,
  workorderCode: null,
  workorderName: null,
  workorderType: 'SELF',
  orderSource: null,
  sourceCode: null,
  productId: null,
  productCode: null,
  productName: null,
  productSpc: null,
  unitOfMeasure: null,
  unitOfMeasureName: null,
  quantity: null,
  quantityProduced: null,
  quantityChanged: null,
  quantityScheduled: null,
  clientId: null,
  clientCode: null,
  clientName: null,
  vendorId: null,
  vendorCode: null,
  vendorName: null,
  requestDate: null,
  parentId: null,
  status: 'PREPARE',
  remark: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  routeId: null
})
const marketId = ref([])
// 用于存储展开行的key
const expandedRows = ref([])
const selectedRows = ref([])  // 存储选中的行
const nodeRelations = ref({}) // 存储节点父子关系 {id: {parentId, childrenIds}}
const lastSyncedKeys = ref(new Set())

const dataTo = reactive({
  // 表单校验
  rules: {
    workorderCode: [
      { required: true, message: '工单编码不能为空', trigger: ['blur', 'change'] },
      { pattern: /^.{1,20}$/, message: '限制1到20个字符', trigger: 'blur' }
    ],
    workorderName: [
      { required: true, message: '工单名称不能为空', trigger: 'blur' },
      { pattern: /^.{1,50}$/, message: '限制1到50个字符', trigger: 'blur' }
    ],
    material: [
      { pattern: /^.{1,300}$/, message: '限制1到300个字符', trigger: 'blur' }
    ],
    weight: [
      { pattern: /^(?:0|[1-9]\d{0,7})(?:\.\d{0,4})?$/, message: '请输入8位整数,4位小数', trigger: ['blur', 'change'] },
      { pattern: /^.{1,20}$/, message: '限制1到20个字符', trigger: 'blur' }
    ],
    workorderType: [
      { required: true, message: '请选择生产工单类型', trigger: 'blur' }
    ],
    orderSource: [
      { required: true, message: '来源类型不能为空', trigger: ['blur', 'change'] }
    ],
    productId: [
      { required: true, message: '产品不能为空', trigger: ['blur', 'change'] }
    ],
    productCode: [
      { required: true, message: '产品编号不能为空', trigger: ['blur', 'change'] }
    ],
    productName: [
      { required: true, message: '产品名称不能为空', trigger: ['blur', 'change'] }
    ],
    quantity: [
      { required: true, message: '生产数量不能为空', trigger: 'blur' }
    ],
    requestDate: [
      { required: true, message: '需求日期不能为空', trigger: 'blur' }
    ],
    batchCode: [
      { pattern: /^.{1,50}$/, message: '限制1到50个字符', trigger: 'blur' }
    ],
    remark: [
      { pattern: /^.{1,300}$/, message: '限制1到300个字符', trigger: 'blur' }
    ],
  },
})


const { rules } = toRefs(dataTo)


// 附件下载地址
const baseUrl = import.meta.env.VITE_APP_BASE_API
// const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action) // 上传的图片服务器地址

// watch(() => route.name, (newName, oldName) => {
//   if (newName === 'Workorder') {
//     setTimeout(() => {
//       getList()
//     }, 700)
//   }
// }
// )

/** 查询生产工单列表 */
function getList() {
  loading.value = true
  listWorkorder(queryParams).then(response => {
    workorderList.value = proxy.handleTree(response.rows, 'workorderId', 'parentId')
    dataTo.total = response.total
    loading.value = false
    // 清空同步记录，因为是新的一页数据
    lastSyncedKeys.value.clear();
  })
  listAllUnitmeasure().then(response => {
    measureOptions.value = response.data
  })
}
getList()
// 单选
function selectRow(selection, row) {
  nextTick(() => {
    const isSelected = selection.includes(row)
    toggleNodeSelection(row, isSelected)
  })
}
// 全选按钮
function selectAllRow(selection, row) {
  // 计算总节点数量（包括所有子节点）
  // 关键步骤：在操作前先同步懒加载的数据到 workorderList
  syncLazyLoadedData();
  const countTotalNodes = (nodes) => {
    let count = 0;
    if (!Array.isArray(nodes)) return count;
    nodes.forEach(node => {
      count++;
      if (node.children && node.children.length > 0) {
        count += countTotalNodes(node.children);
      }
    });
    return count;
  };
  //最关键 确定一页为20 子节点不算
  const totalNodes = countTotalNodes(workorderList.value);
  const currentSelectedCount = countTotalNodes(selection);
  console.log('当前选中:', currentSelectedCount, '总节点:', totalNodes);
  // 判断：如果当前选中数量等于总节点数量，说明是取消全选；否则是全选
  const isRealDeselect = currentSelectedCount < totalNodes;
  const isSelected = currentSelectedCount == totalNodes;
  // 清空所有已选中的行（包括懒加载的子节点）
  proxy.$refs.product.clearSelection();
  // 如果是全选操作，选中所有行
  if (isSelected) {
    // 递归选中所有节点（包括子节点）
    const selectAllRecursive = (nodes) => {
      if (!Array.isArray(nodes)) return;
      nodes.forEach(node => {
        // 选中当前节点
        proxy.$refs.product.toggleRowSelection(node, true);
        // 如果有子节点，递归选中子节点
        if (node.children && node.children.length > 0) {
          selectAllRecursive(node.children);
        }
      });
    };
    // 从根节点开始递归选中
    selectAllRecursive(workorderList.value);
  } else if (isRealDeselect) {
    // 取消全选操作 - 递归取消所有节点
    const deselectRecursive = (nodes) => {
      if (!Array.isArray(nodes)) return;
      nodes.forEach(node => {
        proxy.$refs.product.toggleRowSelection(node, false);
        if (node.children && node.children.length > 0) {
          deselectRecursive(node.children);
        }
      });
    };
    deselectRecursive(workorderList.value);
  }
  // 递归收集所有节点
  const collectAllNodes = (nodes) => {
    return nodes.reduce((all, node) => {
      all.push(node);
      if (node.children && node.children.length > 0) {
        all.push(...collectAllNodes(node.children));
      }
      return all;
    }, []);
  };
  // 更新状态
  const allNodes = collectAllNodes(workorderList.value);
  selectedRows.value = isRealDeselect ? [] : allNodes;
  ids.value = selectedRows.value.map(item => item.workorderId);
  single.value = selectedRows.value.length !== 1;
  multiple.value = !selectedRows.value.length;
  flowcard.value = !selectedRows.value.length;

  console.log('操作结果:', isRealDeselect ? '取消全选' : '全选', '选中', ids.value.length, '个节点');

}

function toggleNodeSelection(node, isSelected) {
  // 设置当前节点选择状态
  proxy.$refs.product.toggleRowSelection(node, isSelected)
  // 自动选择所有子节点
  toggleChildrenSelection(node, isSelected)
  // 自动更新父节点状态
  updateParentSelection(node)
}

// 优化后的同步方法
function syncLazyLoadedData() {
  const { store } = proxy.$refs.product;
  if (!store || !store.states || !store.states.lazyTreeNodeMap) {
    return;
  }

  const lazyMap = store.states.lazyTreeNodeMap;
  let hasNewData = false;
  const syncDataRecursive = (nodes) => {
    if (!Array.isArray(nodes)) return;
    nodes.forEach(node => {
      const nodeKey = getRowKeys(node);

      // 检查这个节点的子节点数据是否已经同步过
      if (lazyMap[nodeKey] && lazyMap[nodeKey].length > 0 &&
        !lastSyncedKeys.value.has(nodeKey)) {
        node.children = lazyMap[nodeKey]
        lastSyncedKeys.value.add(nodeKey);
        hasNewData = true;

        // 递归同步子节点
        if (node.children && node.children.length > 0) {
          syncDataRecursive(node.children);
        }
      } else if (node.children && node.children.length > 0) {
        syncDataRecursive(node.children);
      }
    });
  };

  syncDataRecursive(workorderList.value);

  if (hasNewData) {
    console.log('同步了新的懒加载数据');
  }
}

// 切换子节点选择状态
function toggleChildrenSelection(node, isSelected) {
  const childrenIds = nodeRelations.value[node.workorderId]?.childrenIds || []
  childrenIds.forEach(childId => {
    const child = findNodeById(childId)
    if (child) {
      proxy.$refs.product.toggleRowSelection(child, isSelected)
      toggleChildrenSelection(child, isSelected)
    }
  })
}
// 加载并选择子节点
function loadAndSelectChildren(node, isSelected) {
  return new Promise(resolve => {
    proxy.$refs.product.store.loadOrToggle(node, () => {
      const childrenIds = nodeRelations.value[node.workorderId]?.childrenIds || []
      childrenIds.forEach(childId => {
        const child = findNodeById(childId)
        if (child) {
          proxy.$refs.product.toggleRowSelection(child, isSelected)
        }
      })
      resolve()
    }, true) // 强制展开
  })
}

// 更新父节点选择状态
function updateParentSelection(node) {
  const parentId = nodeRelations.value[node.workorderId]?.parentId
  if (!parentId) return
  const parent = findNodeById(parentId)
  if (!parent) return
  const childrenIds = nodeRelations.value[parentId]?.childrenIds || []
  const allChildrenSelected = childrenIds.every(childId => {
    return selectedRows.value.some(row => row.workorderId === childId)
  })
  proxy.$refs.product.toggleRowSelection(parent, allChildrenSelected)
  // 递归向上更新
  updateParentSelection(parent)
}
// 根据ID查找节点
function findNodeById(id) {
  // 先在当前页数据中查找
  const findInTree = (nodes) => {
    for (const node of nodes) {
      if (node.workorderId === id) return node
      if (node.children) {
        const found = findInTree(node.children)
        if (found) return found
      }
    }
    return null
  }
  return findInTree(workorderList.value)
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRows.value = selection
  ids.value = selection.map(item => item.workorderId)
  ids.value = [...new Set(ids.value)]
  single.value = selection.length !== 1
  multiple.value = !selection.length
  flowcard.value = !selection.length
  const arr = selection.filter(items => items.status !== 'PREPARE')
  if (arr.length >= 1) {
    single.value = true
    multiple.value = true
    // this.$modal.msgError("只能删除")
  }
}
/**
* @getRowKeys 设置回显的函数
* @parmas row 当前行的数据，需要一个唯一的标识来标记是哪一个被选中了
*/
function getRowKeys(row) {
  return row.workorderId
}


/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  if (column.prop == 'productName') {
    // 产品名称
    queryParams.sortField = 'productName'
    if (column.order === 'descending') {
      queryParams.isAsc = 'desc'
    } else {
      queryParams.isAsc = 'asc'
    }
  }
  if (column.prop == 'quantity') {
    // 工单数量
    queryParams.sortField = 'quantity'
    if (column.order === 'descending') {
      queryParams.isAsc = 'desc'
    } else {
      queryParams.isAsc = 'asc'
    }
  }
  if (column.prop == 'requestDate') {
    // 需求日期 ascending
    queryParams.sortField = 'quantity'
    if (column.order === 'descending') {
      queryParams.isAsc = 'desc'
    } else {
      queryParams.isAsc = 'asc'
    }
  }
  getList()
}

/** 转换生产工单数据结构 */
function normalizer(node) {
  if (node.children && !node.children.length) {
    delete node.children
  }
  return {
    id: node.workorderId,
    label: node.workorderName,
    children: node.children
  }
}


/** 查询生产工单下拉树结构 */
function getTreeselect() {
  listWorkorder().then(response => {
    workorderOptions.value = []
    const data = { workorderId: 0, workorderName: '顶级节点', children: [] }
    workorderOptions.value.push(data)
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {

  let forms = {
    workorderId: null,
    workorderCode: null,
    workorderName: null,
    workorderType: 'SELF',
    orderSource: null,
    sourceCode: null,
    productId: null,
    productCode: null,
    productName: null,
    productSpc: null,
    unitOfMeasure: null,
    unitOfMeasureName: null,
    quantity: null,
    quantityProduced: null,
    quantityChanged: null,
    quantityScheduled: null,
    clientId: null,
    clientCode: null,
    clientName: null,
    vendorId: null,
    vendorCode: null,
    vendorName: null,
    requestDate: null,
    parentId: null,
    status: 'PREPARE',
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    routeId: null
  }

   Object.keys(forms).forEach(key => {
    form.value[key] = forms[key]
  })
  // proxy.$refs['form'].clearValidate()
  autoGenFlag.value = false
  // this.resetForm('form')
  // nextTick(() => {
  //   proxy.$refs['form'].clearValidate() // 为了清除校验的提示
  // })
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryForm')
  queryParams.sortField = null,
    queryParams.isAsc = null,
    handleQuery()
}

// 从BOM行中直接新增
function handleSubAdd(row) {
  open.value = false
  reset()
  getTreeselect()
  if (row != null && row.workorderId) {
    form.value = row
    form.value.parentId = row.workorderId
    form.value.workorderId = null
    form.value.workorderCode = null
    form.value.unitOfMeasureName = proxy.selectunitOfMeasure(measureOptions.value, row.unitOfMeasure)
  } else {
    form.value.parentId = 0
  }
  open.value = true
  title.value = '添加生产工单'
  optType.value = 'add'
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  getTreeselect()
  if (row != null && row.workorderId) {
    form.value.parentId = row.workorderId
    form.value.orderSource = row.orderSource
    form.value.sourceCode = row.sourceCode
    form.value.clientId = row.clientId
    form.value.clientCode = row.clientCode
    form.value.clientName = row.clientName
  } else {
    form.value.parentId = 0
  }
  open.value = true
  title.value = '添加生产工单'
  optType.value = 'add'
  console.log(open.value)
}

// 查询明细按钮操作
function handleView(row) {
  reset()
  getTreeselect()
  const workorderId = row.workorderId || ids.value
  getWorkorder(workorderId).then(response => {
    form.value = response.data
    form.value.unitOfMeasureName = proxy.selectunitOfMeasure(measureOptions.value, response.data.unitOfMeasure)
    open.value = true
    title.value = '查看工单信息'
    optType.value = 'view'
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  getTreeselect()
  if (row != null) {
    form.value.parentId = row.workorderId
  } else {
    form.value.parentId = ids.value
  }
  const recordId = row.workorderId || ids.value
  getWorkorder(recordId).then(response => {
    form.value = response.data
    form.value.unitOfMeasureName = proxy.selectunitOfMeasure(measureOptions.value, response.data.unitOfMeasure)
    open.value = true
    title.value = '修改生产工单'
    optType.value = 'edit'
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      if (form.value.routeId === null || form.value.routeId === undefined || form.value.routeId === undefined) {
        proxy.$modal.msgError('请选择工艺路线')
        return
      }
      if (form.value.workorderId != null) {
        updateWorkorder(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          proxy.$refs['bomlist'].getList()
          getList()
        })
      } else {
        addWorkorder(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          form.value.workorderId = response.data
          getList()
        })
      }
    }
  })
}



/** 删除按钮操作 */
function handleDelete(row) {
  const recordIds = row.workorderId || ids.value
  proxy.$modal.confirm('确认删除数据项？').then(function () {
    return delWorkorder(recordIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {
  })
}


function handleSelectProduct() {
  proxy.$refs.itemSelect.showFlag = true
}

function handleSelectClient() {
  proxy.$refs.clientSelect.showFlag = true
}

/** 导出按钮操作 */
function handleExport() {
  download('mes/pro/workorder/export',
    { workorderIds: ids.value.join(',') },
    `workorder_${new Date().getTime()}.xlsx`)
}

function handleConfirm() {
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      if (form.routeId === null || form.routeId === undefined || form.routeId === undefined) {
        proxy.$modal.msgError('请选择工艺路线')
        return
      }
      proxy.$modal.confirm('是确认完成工单编制？【确认后将不能更改】').then(function () {
        form.status = 'CONFIRMED'
        updateWorkorder(form).then(response => {
          open.value = false
          proxy.$refs['bomlist'].getList()
          getList()
        })
      })
    }
  })
}

function handleFinish(row) {
  const workorderIds = row.workorderId || ids.value
  proxy.$modal.confirm('确认完成工单？一旦完成，此工单将无法继续报工').then(function () {
    return dofinish(workorderIds) // 完成工单
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('更改成功')
  }).catch(() => {

  })
}

// 物料选择弹出框
function onItemSelected(obj) {
  if (obj != undefined && obj != null) {
    form.productId = obj.itemId
    form.productCode = obj.itemCode
    form.productName = obj.itemName
    form.productSpc = obj.specification
    form.unitOfMeasure = obj.unitOfMeasure
    form.unitOfMeasureName = proxy.selectunitOfMeasure(measureOptions.value, obj.unitOfMeasure)
  }
}

// 客户选择弹出框
function onClientSelected(obj) {
  if (obj != undefined && obj != null) {
    form.clientId = obj.clientId
    form.clientCode = obj.clientCode
    form.clientName = obj.clientName
    findOrderqueryParams.clientCode = obj.clientCode
  }
}

function onClientSelectedOrder(obj) {
  findOrderqueryParams.clientCode = obj.clientCode
  findOrderqueryParams.clientName = obj.clientName
}
// 供应商选择
function handleSelectVendor() {
  proxy.$refs.vendorSelect.showFlag = true
}

// 供应商选择弹出框
function onVendorSelected(obj) {
  if (obj != undefined && obj != null) {
    form.vendorId = obj.vendorId
    form.vendorCode = obj.vendorCode
    form.vendorName = obj.vendorName
  }
}

// 自动生成编码
function handleAutoGenChange(autoGenFlag) {
  if (autoGenFlag) {
    genCode('WORKORDER_CODE').then(response => {
      form.workorderCode = response
    })
  } else {
    form.workorderCode = null
  }
}
// 工艺流程返回
function prorouteSelected(e) {
  form.routeId = e.routeId
}

/**
 * 单位翻译
 */
function unitOfMeasure(row) {
  return proxy.selectunitOfMeasure(measureOptions.value, row.unitOfMeasure)
}


function dataformatter(row, column, cellValue, index) {
  if (cellValue == '' || cellValue == undefined || cellValue == null) {
    return '--'
  } else {
    return cellValue
  }
}


function requestDate(row) {
  if (row.requestDate) {
    return proxy.parseTime(row.requestDate, '{y}-{m}-{d}')
  } else {
    return '--'
  }
}

function orderSource(row) {
  if (row.orderSource) {
    return proxy.selectDictLabel(mes_workorder_sourcetype.value, row.orderSource)
  } else {
    return '--'
  }
}

function quantityChanged(row) {
  if ((row.quantityChanged ?? '') !== '') {
    return row.quantityChanged
  } else {
    return '--'
  }
}
// 打印
function downloads() {
  const arr = ids.value.join(',')
  if (ids.value.length > 0) {
    exportPdf({ workorderIds: arr }).then(res => {
      if (res.code == 200) {
        exceldownload(res.msg)
      }
    })
  }
}


// 查看
function downloadView(row) {
  preview.value = true
  textVisibleURl.value = baseUrl.value +
    '/mes/pro/workorder/findworkOrderDetail?workorderId=' + row.workorderId
}
function handleClose() {
  proxy.$confirm('是否关闭当前页面').then(res => {
    cancel()
  })
}


function marketgetRowKeys(row) {
  return row.id
}
function marketGet() {
  const today = moment()
  // 获取前30天的日期
  const thirtyDaysAgo = today.clone().subtract(30, 'days')
  // 设置开始日期为前30天的开始时间（即00:00:00）
  var startDate = thirtyDaysAgo.startOf('day').format('YYYY-MM-DD')
  // 设置结束日期为当前日期的开始时间（即00:00:00），因为我们是从前30天开始计算的，所以这里实际上是今天的前一天晚上11:59:59，但为了完整性，我们将它设置为当天的开始时间）
  var endDate = today.clone().startOf('day').subtract(1, 'seconds').format('YYYY-MM-DD') // 使用subtract(1, 'seconds')是为了确保包含今天的最后时刻
  console.log(startDate, endDate)
  findOrderqueryParams.voucherDate = [startDate, endDate]
  market.value = true
  marketListGet()
}

// 销售订单列表
function marketListGet() {
  marketloading.value = true
  addFromloading.value = false
  const arr = {
    pageNum: findOrderqueryParams.pageNum,
    pageSize: findOrderqueryParams.pageSize,
    startTime: findOrderqueryParams.voucherDate ? findOrderqueryParams.voucherDate[0] : undefined,
    endTime: findOrderqueryParams.voucherDate ? findOrderqueryParams.voucherDate[1] : undefined,
    code: findOrderqueryParams.code || undefined,
    customerCode: findOrderqueryParams.clientCode || undefined
  }
  findOrderList(arr).then(res => {
    if (res.code === 200) {
      res.rows.map(item => {
        item.ruleItemData = []
      })
      marketList.value = res.rows
      findOrderqueryParams.total = res.total
      marketloading.value = false
    } else if (res.code === 500) {
      marketloading.value = false
    }
  }).catch(err => {
    marketloading.value = false
  })
}



// 展开单元格点击
function expandGet(row, expandedRows) {
  if (expandedRows.length > 0) {
    marketloading.value = true
    findItemByCode({ code: row.code }).then(res => {
      if (res.code === 200) {
        // 遍历当前页面表
        marketList.value.forEach((temp, index) => {
          // 找到当前点击的行，把动态获取到的数据赋值进去
          if (temp.code === row.code) {
            marketList.value[index].ruleItemData = res.rows
          }
        })
        setTimeout(() => {
          marketloading.value = false
        }, 200)
      }
    })
  }
}

function voucherDate(row) {
  if (row.voucherDate) {
    return proxy.parseTime(row.voucherDate, '{y}-{m}-{d}')
  } else {
    return '--'
  }
}

function generalData(row, column, cellValue, index) {
  if (cellValue == '' || cellValue == undefined || cellValue == null) {
    return '--'
  } else {
    return cellValue
  }
}

// 销售订单多选
function marketSelectionChange(selection) {
  // //订单
  // order:0,
  // //存货
  // inventory:0,
  if (selection.length > 0) {
    order.value = selection.length
    marketId.value = selection.map(item => item.id)
    dataTo.code = selection.map(item => item.code)
    inventory.value = selection.reduce((sum, item) => {
      return sum + item.count
    }, 0)
  } else {
    order.value = 0
    inventory.value = 0
  }
}

// 生成订单
function addFromErpOrderGet() {
  if (marketId.value.length > 0) {
    addFromloading.value = true
    addFromErpOrder({ code: dataTo.code.join(',') }).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('生成订单成功')
        market.value = false
        order.value = 0
        marketId.value = []
        dataTo.code = []
        inventory.value = 0
        proxy.$refs.marketable.clearSelection()
        expandedRows.value = []
      } else {
        proxy.msgError(res.msg)
      }
      getList()
      addFromloading.value = false
    }).catch(err => {
      // this.msgError(err.msg)
      getList()
      market.value = false
      order.value = 0
      marketId.value = []
      dataTo.code = []
      inventory.value = 0
      proxy.$refs.marketable.clearSelection()
      expandedRows.value = []
      addFromloading.value = false
    })
  } else {
    proxy.$modal.msgError('请选择销售订单')
  }
}

function marketListGetresetQuery() {
  const today = moment()
  // 获取前30天的日期
  const thirtyDaysAgo = today.clone().subtract(30, 'days')
  // 设置开始日期为前30天的开始时间（即00:00:00）
  var startDate = thirtyDaysAgo.startOf('day').format('YYYY-MM-DD')
  // 设置结束日期为当前日期的开始时间（即00:00:00），因为我们是从前30天开始计算的，所以这里实际上是今天的前一天晚上11:59:59，但为了完整性，我们将它设置为当天的开始时间）
  var endDate = today.clone().startOf('day').subtract(1, 'seconds').format('YYYY-MM-DD') // 使用subtract(1, 'seconds')是为了确保包含今天的最后时刻
  findOrderqueryParams = {
    pageNum: 1,
    pageSize: 20,
    total: 0,
    voucherDate: [startDate, endDate],
    startTime: '',
    endTime: '',
    code: '',
    customerName: '',
    customerCode: ''
  }
  marketListGet()
}



function findOrderClose() {
  order.value = 0
  expandedRows.value = []
  marketId.value = []
  dataTo.code = []
  inventory.value = 0
  proxy.$refs.marketable.clearSelection()
}
function load(tree, treeNode, resolve) {
  getChildList({ parentId: tree.workorderId }).then(res => {
    nodeRelations.value[tree.workorderId] = nodeRelations.value[tree.workorderId] || {}
    nodeRelations.value[tree.workorderId].childrenIds = res.map(c => c.workorderId)
    res.forEach(child => {
      nodeRelations.value[child.workorderId] = {
        parentId: tree.workorderId
      }
    })
    resolve(res)
    // 存储加载的节点，用于后续全选
    tree.children = res;
  })
}

</script>
<style lang="scss" scoped>
:deep(.el-table__cell) {
  position: relative;
}

.orderinventory {
  display: inline-block;
  margin-right: 20px;
}

.device-state {
  position: absolute;
  line-height: 20px;
  top: 0;
  right: 0;
  font-size: 11px;
}

.device-state-color1 {
  padding: 0 8px;
  background: rgba(255, 74, 90, 0.32);
  color: #FF4A5A;
}

.device-state-color2 {
  padding: 0 8px;
  background: rgb(251, 128, 46, 0.32);
  color: #FB802EFF;
}

.div_tre {
  display: inline-block;
  width: 130px;
  line-height: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #294088;
  cursor: pointer;
}
</style>
